<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	ENDNOTE (tabbed file) export class
*
*	$Header: /cvsroot/wikindx/wikindx3/core/file/export/ENDNOTE.php,v 1.15 2006/03/25 22:18:22 sirfragalot Exp $
*****/
class ENDNOTE
{
/*
* Constructor
*
* @author Mark Grimshaw
* @version 2
*/
// Constructor
	function ENDNOTE($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/file/FILE.php");
		$this->file = new FILE($this->db);
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/file/ENDNOTEMAP.php");
		$this->map = new ENDNOTEMAP();
		include_once("core/file/export/EXPORTCOMMON.php");
		$this->common = new EXPORTCOMMON($this->db);
//		include_once("core/messages/UTF8.php");
//		$this->utf8 = new UTF8();
		$this->pString = '';
// Perform some system admin
		$this->file->tidyFiles();
	}
// Stage 1 - present export options
	function stage1()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "exportEndnote"));
		if(!$sql = $this->session->getVar('sql_stmt'))
			$this->failure($this->errors->text("file", "noSql"));
		$pString = FORM::formHeader("exportEndnote");
		$checked = $this->session->getVar("export_mergeStored") ? TRUE : FALSE;
		$pString .= MISC::p($this->messages->text("misc", "mergeStored") . "&nbsp;&nbsp;" . 
			FORM::checkbox(FALSE, "mergeStored", $checked));
		$pString .= MISC::br() . FORM::formSubmit('Submit');
		$pString .= FORM::formEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// write $this->pString to file.  If file exists, it is written over.
	function process()
	{
		if(isset($this->vars['mergeStored']))
			$this->session->setVar('export_mergeStored', $this->vars['mergeStored']);
		else
			$this->session->delVar('export_mergeStored');
		$this->template->setVar('heading', $this->messages->text("heading", "exportEndnote"));
		$this->getData();
		list($fileName, $fullFileName) = $this->file->createFileName($this->pString, '.txt');
		if(!$fullFileName)
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		if(!$fp = fopen("$fullFileName", "w"))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		if(!fputs($fp, $this->pString))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		fclose($fp);
		$this->common->writeFilenameToSession($fileName);
		$pString = $this->common->listFiles();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// get data from database
	function getData()
	{
// load default arrays (English constants, day and month conversions etc.
		$this->loadArrays();
// Initial generic field
		$this->pString = "*Generic\r";
// Get all possible field names from $this->map
		$fieldNameArray = $this->map->generic;
		$exportRawFields = $this->map->exportRawFields;
// Put 'Reference Type' at the front
		array_unshift($fieldNameArray, 'Reference Type');
// Get last SQL statement from session.
		if(!$sql = $this->session->getVar('sql_stmt'))
			$this->failure($this->errors->text("file", "noSql"));
		$recordset = $this->db->query(stripslashes($sql));
/**
* Need to get raw data first and add its keys to $fieldNameArray
**/
		if($this->session->getVar("export_mergeStored"))
		{
			while($row = $this->db->loopRecordSet($recordset))
			{
				if($raw = $this->raw($row))
				{
					foreach($raw as $key => $value)
					{
						if(!array_key_exists($key, $exportRawFields))
							continue;
						$key = $exportRawFields[$key];
						if(array_search($key, $fieldNameArray) === FALSE)
							$fieldNameArray[] = $key;
					}
					$rawEntries[$row['resourceId']] = $raw;
				}
			}
		}
// Field names line
		$this->pString .= join("\t", $fieldNameArray) . "\r";
		$recordset = $this->db->query(stripslashes($sql));
		while($row = $this->db->loopRecordSet($recordset))
		{
			$this->authorFound = FALSE;
			$lineArray = $this->rawEntries = array();
//			$this->raw($row);
			for($index = 0; $index < sizeof($fieldNameArray); $index++)
				$lineArray[] = '';
// Do we need to switch `year1` (publicationYear) and `year2` (reprintYear)
			if((($row['type'] == 'book') || ($row['type'] == 'book_article'))
				&& $row['year1'] && $row['year2'])
			{
				$tempYear2 = $row['year2'];
				$row['year2'] = $row['year1'];
				$row['year1'] = $tempYear2;
			}
// else, always use `year2` (conference year etc.) in preference to `year1` except for web_article
			else if($row['year2'] && ($row['type'] != 'web_article'))
			{
				$row['year1'] = $row['year2'];
				unset($row['year2']);
			}
			foreach($this->map->{$row['type']} as $table => $tableArray)
			{
				if($table == 'resource_creator')
					continue;
				foreach($tableArray as $wkField => $enField)
				{
					$fieldNameIndex = array_search($enField, $fieldNameArray);
					if(isset($row[$wkField]) && $row[$wkField])
						$lineArray[$fieldNameIndex] = stripSlashes($row[$wkField]);
				}
			}
// We now have an array padded with blank elements and filled with populated fields for that resource in 
// the correct order.  Have to add in the special fields we array_merged above.
			$lineArray[array_search('Title', $fieldNameArray)] = $this->common->titleFormat($row);
			foreach($this->map->{$row['type']}['resource_creator'] as $wkCreator => $enCreator)
			{
				if(!$creators = $this->nameFormat($row, $wkCreator))
					continue;
				if(!$this->authorFound and ($row['type'] == 'book')) // 'Edited Book'
					$lineArray[array_search('Author', $fieldNameArray)] = $creators;
				else
					$lineArray[array_search($enCreator, $fieldNameArray)] = $creators;
			}
// Reference Type.  If !$this->authorFound and $row['type'] == 'book', this is actually 
// Endnote's 'Edited Book' type.
			if(!$this->authorFound and ($row['type'] == 'book'))
				$lineArray[array_search('Reference Type', $fieldNameArray)] = 'Edited Book';
			else
				$lineArray[array_search('Reference Type', $fieldNameArray)] = 
					stripslashes($this->map->types[$row['type']]);
// web_article Access Year is stored in 'Volume' and Access Date in 'Number'
			$this->dateFormat($row, $lineArray, $fieldNameArray);
			$lineArray[array_search('Pages', $fieldNameArray)] = $this->common->pageFormat($row, 'endnote');
			$lineArray[array_search('Keywords', $fieldNameArray)] = 
				$this->common->keywordFormat($row, 'endnote');
			$lineArray[array_search('Abstract', $fieldNameArray)] = 
				$this->common->grabAbstract($row, 'endnote');
			$lineArray[array_search('Notes', $fieldNameArray)] = 
				$this->common->grabNote($row, 'endnote');
// Do we want to export previously saved unused fields?
			if(!empty($rawEntries) && array_key_exists($row['resourceId'], $rawEntries))
			{
				foreach($rawEntries[$row['resourceId']] as $key => $value)
				{
// WIKINDX stores only integer type dates and will reject other types such as 'Spring'. If we're exporting raw entries and a 'Date' field exists in $rawEntries 
// and there is 'Date' field being used in $lineArray, insert $rawEntries['Date']
					if(($key == 'Date') && !$lineArray[array_search('Date', $fieldNameArray)])
						$lineArray[array_search('Date', $fieldNameArray)] = $value;
					else if(array_key_exists($key, $exportRawFields))
						$lineArray[array_search($exportRawFields[$key], $fieldNameArray)] = $value;
				}
			}
			$this->pString .= join("\t", $lineArray) . "\r";
		}
	}
// format names.
	function nameFormat($row, $type)
	{
		if(!isset($row[$type]) || !$row[$type])
			return '';
		if($type == 'creator1') // author
			$this->authorFound = TRUE;
		$creatorIds = explode(",", $row[$type]);
		foreach($creatorIds as $id)
			$condition[] = $this->db->formatField('id') . "=" . $this->db->tidyInput($id);
		$recordset = $this->db->select(array('WKX_creator'), 
			array('surname', 'firstname', 'initials', 'prefix', 'id'), 
			" WHERE " . implode(' OR ', $condition));
		if($this->db->numRows($recordset))
		{
			$nameArray = array();
			while($creatorRow = $this->db->loopRecordset($recordset))
			{
				$name = $this->common->formatName($creatorRow, 'endnote');
				if($name)
					$mapName[$creatorRow['id']] = $name;
			}
			foreach($creatorIds as $id)
				$nameArray[] = $mapName[$id];
			return join("//", $nameArray);
		}
		return ''; // We shouldn't get here but just in case...
	}
// format date for newspaper/magazine etc.
	function dateFormat($row, &$lineArray, $fieldNameArray)
	{
		if($row['type'] == 'web_article')
// Access Year -> 'Volume' and access date -> 'Number'
		{
			$day = $month = FALSE;
			if($row['miscField3'])
				$month = $this->monthArray[$row['miscField3']];
			if($row['miscField2'])
				$day = $row['miscField2'] < 10 ? '0' . $row['miscField2'] : $row['miscField2'];
			if($month)
				$lineArray[array_search('Number', $fieldNameArray)] =  $month . ' ' . $day;
			$lineArray[array_search('Volume', $fieldNameArray)] =  $row['year1'];
		}
		else if(isset($row['year1']) && $row['year1'] && $row['miscField3'])
		{
			$date[] = $this->monthArray[$row['miscField3']];
			if($row['miscField2'])
				$date[] = $row['miscField2'] < 10 ? '0' . $row['miscField2'] : $row['miscField2'];
			$lineArray[array_search('Date', $fieldNameArray)] =  join(' ', $date);
		}
	}
// grab any stored data for this resource from WKX_import_raw
	function raw($row)
	{
		$recordset = $this->db->select(array('WKX_import_raw'), array('text', 'importType'), 
			"WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['resourceId']) . 
			" AND " . $this->db->formatField('importType') . "=" . $this->db->tidyInput('endnote'));
		if(!$this->db->numRows($recordset))
			return FALSE;
		while($rawRow = $this->db->loopRecordSet($recordset))
			$rawEntries = unserialize(base64_decode($rawRow['text']));
		if($rawEntries)
		{
			$rawEntries = explode("\n", $rawEntries);
			array_pop($rawEntries); // always an empty array at end so get rid of it.
			foreach($rawEntries as $entries)
			{
				$entry = explode("=", $entries, 2);
				if(!trim($entry[1]))
					continue;
				if(trim($entry[0]) == 'citation')
					$this->rawCitation = trim($entry[1]);
				else
				{
					$key = trim($entry[0]);
					$value = trim($entry[1]);
					$rawEntry[$key] = $value;
				}
			}
		}
		if(isset($rawEntry))
			return $rawEntry;
		return FALSE;
	}
// load default arrays
	function loadArrays()
	{
// need to use English constants for ENDNOTE
		include_once("languages/en/CONSTANTS.php");
		$constants = new CONSTANTS_en();
		$constants->convertNumbers();
		$this->editionArray = $constants->cardinalToOrdinalWord();
		$this->monthArray = $constants->monthToLongName();
	}
// Error handling
	function failure($error)
	{
		$this->template->setVar('body', $error);
		$pString = $this->template->process();
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $pString);
	}
}
?>
